# -*- coding:utf-8 -*-
import re
from random import randint

from flask import request, current_app, make_response, jsonify, render_template, session

from app.models import User
from app.utils.response_code import RET
from datetime import datetime

__author__ = "Jim"

"""
Create by Jim on2018/12/30
"""
from app.utils.captcha.captcha import captcha
from . import passport_blueprint
from app import redis_store, constants, db


@passport_blueprint.route('/register', methods=['POST'])
def register():
    param_dict = request.json
    mobile = param_dict.get('mobild')
    sms_code = param_dict.get('sms_code')
    password = param_dict.get('password')

    smscode = redis_store.get('SMS_' + mobile)
    if not all([mobile, sms_code, password]):
        return jsonify(errno=RET.DATAERR, errmsg="每一项都必填")
    if not len(password) >= 6:
        return jsonify(errno=RET.DATAERR, errmsg="密码长度不够")
    user = None
    if sms_code == smscode:
        user = User()
        user.nick_name = mobile
        user.mobile = mobile
        user.password = password
        user.last_login = datetime.now()
        db.session.add(user)
        db.session.commit()
        session["user_id"] = user.id
        return jsonify(errno=RET.OK, errmsg="注册成功")
    return render_template('news/index.html', user=user)


@passport_blueprint.route('/login')
def login():
    data = request.json
    mobile = data.get('mobile')
    password = data.get('password')
    try:
        user = User.query.filter_by(mobile=mobile).frist()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据错误")

    if not user:
        return jsonify(errno=RET.DBERR, errmsg="用户不存在")
    if user.check_passowrd(password):
        session["user_id"] = user.id
        session["nick_name"] = user.nick_name
        session["mobile"] = user.mobile
        user.last_login = datetime.now()
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
        return jsonify(errno=RET.OK, errmsg="登陆成功")
    return render_template('news/index.html', user=user)


@passport_blueprint.route('/sms_code', methods=['POST'])
def sms_code():
    param_dict = request.json
    mobile = param_dict.get("mobile")
    image_code = param_dict.get("image_code")
    image_code_id = param_dict.get("image_code_id")

    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if not re.match("^1[3578][0-9]{9}$", mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机号不正确")

    try:
        redis_image_code = redis_store.get("image_code:" + image_code_id)
        if redis_image_code:
            # redis_image_code = redis_image_code()
            redis_store.delete("image_code:" + image_code_id)
        else:
            return jsonify(errno=RET.DBERR, errmsg="图片验证码已过期")

    except Exception as e:

        current_app.logger.error(e)

        # 获取图片验证码失败

        return jsonify(errno=RET.DBERR, errmsg="获取图片验证码失败")

    if redis_image_code.upper() == image_code.upper():
        try:
            from app.models import User
            user = User.query.filter_by(mobile=mobile).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
        if user:
            # 该手机已被注册
            return jsonify(errno=RET.DATAEXIST, errmsg="该手机已被注册")
    else:
        return jsonify(errno=RET.DBERR, errmsg="验证码输入错误")

    res = randint(1000, 9999)
    smscode = "%06d" % res
    current_app.logger.debug("短信验证码的内容：%s" % smscode)

    try:
        redis_store.set("SMS_" + mobile, smscode, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        # 保存短信验证码失败
        return jsonify(errno=RET.DBERR, errmsg="保存短信验证码失败")

        # 7. 返回发送成功的响应
    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_blueprint.route('/image_code')
def image_code():
    # 1.获取前端传递的参数
    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")

    # 2.调用generate_captcha获取图片验证码编号,验证码值,图片(二进制)
    _, code, img_code = captcha.generate_captcha()

    # 3.将图片验证码的值保存redis
    try:
        # 参数1: key,  参数2: value,  参数3: 有效期
        redis_store.set("image_code:%s" % cur_id, code, constants.IMAGE_CODE_REDIS_EXPIRES)

        # 4.判断是否有上一次的图片验证码
        if pre_id:
            redis_store.delete("image_code:%s" % pre_id)
    except Exception as e:
        current_app.logger.error(e)
        return "图片验证码操作失败"

    response = make_response(img_code)
    response.headers = {'Content-Type': 'image/png'}
    return response
